package com.usian.search.service.impl;

import com.usian.model.search.dtos.UserSearchDto;
import com.usian.search.entity.ApUserSearch;
import com.usian.search.mapper.ApUserSearchMapper;
import com.usian.search.service.IApUserSearchService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * APP用户搜索信息表 服务实现类
 * </p>
 *
 * @author usian
 * @since 2022-10-19
 */
@Service
public class ApUserSearchServiceImpl extends ServiceImpl<ApUserSearchMapper, ApUserSearch> implements IApUserSearchService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    //Redis存储数据的业务前缀
    private String PRE_FIX = "ld:search:word:";

    /**
     * 构造zset的key
     * @param dto
     * @param userId
     * @return
     */
    private String getRedisKey(UserSearchDto dto, Integer userId) {
        String key = "";
        if(userId != null){
            key = userId.toString();
        }else{
            key = dto.getEquipmentId();
        }
        key = PRE_FIX + key ;
        return key;
    }

    @Async("taskExecutor")//异步记录搜索历史
    @Override
    public void saveUserSearch(UserSearchDto dto, Integer userId) {
        //获取Redis中的key值
        String key = getRedisKey(dto, userId);
        //基于Redis的zset数据类型保存搜索历史，需要把score分值递增
        redisTemplate.boundZSetOps(key).incrementScore(dto.getSearchWords(),1);
        //可以设置有效期为7天
        redisTemplate.expire(key,7, TimeUnit.DAYS);
    }

    @Override
    public Set<String> findUserSearch(UserSearchDto dto, Integer userId) {
        //获取Redis中的key值
        String key = getRedisKey(dto, userId);
        Set<String> set = redisTemplate.boundZSetOps(key).reverseRange(0, -1);
        //redisTemplate.opsForZSet().reverseRange(key,0,-1);
        return set;
    }

    @Override
    public void removeUserSearch(UserSearchDto dto, Integer userId) {
        //获取Redis中的key值
        String key = getRedisKey(dto, userId);
        redisTemplate.boundZSetOps(key).remove(dto.getSearchWords());
    }
}
